package cn.org.itool.ws.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.org.itool.common.utils.CollectionOperationsUtil;
import cn.org.itool.common.utils.MapDecoratorUtil;
import cn.org.itool.ws.framework.utils.ChannelGroupUtil;
import cn.org.itool.ws.pojo.UserTag;

import java.util.*;

public class TagUtil {

    public static List<String> listUserIdBySpaceId(String spaceId, String expression) {

        Set<UserTag> userTagVOS = get(spaceId);
        if(CollectionUtil.isEmpty(userTagVOS)) {
            return null;
        }
        Map<String, Set<String>> userIdByTagMap = new HashMap<>();
        for (UserTag userTagVO : userTagVOS) {
            String userId = userTagVO.getUserId();
            for (String tag : userTagVO.getTags()) {
                Set<String> userIds = userIdByTagMap.computeIfAbsent(tag, id -> new HashSet<>());
                userIds.add(userId);
            }
        }
        MapDecoratorUtil<String, Set<String>> mapDecorator = MapDecoratorUtil.valueOf(userIdByTagMap);
        List<List<String>> list = cn.org.itool.common.utils.TagUtil.parse(expression);
        Set<Set<String>> intersection = new HashSet<>();
        for (List<String> stringList : list) {
            // 取交集
            Set<Set<String>> set = mapDecorator.getAll(stringList);
            Set<String> userIds = CollectionOperationsUtil.intersection(set);
            intersection.add(userIds);
        }
        // 取并集
        return new ArrayList<>(CollectionOperationsUtil.union(intersection));
    }

    public static Set<UserTag> get(String spaceId) {
        return ChannelGroupUtil.getUserTagByName(spaceId);
    }
}
